<?php
namespace PsiFramework\Applications\AlloMediaPortal\Classes\DAO;

import("Classes.DAO.AbstractDAO");
import("Applications.AlloMediaPortal.Classes.Model.SiteMembership");

use \PsiFramework\Classes\DAO\AbstractDAO;
use \PsiFramework\Classes\Model\Object;
use \PsiFramework\Classes\Util\Database\Builder\QueryBuilder;
use \PsiFramework\Classes\Util\Database\Filters\QueryFilter;
use \PsiFramework\Classes\Util\Database\Query\SqlColumn;
use \PsiFramework\Classes\Util\Database\Query\SqlFunction;
use \PsiFramework\Classes\Util\Database\Query\SqlOperation;
use \PsiFramework\Classes\Util\Database\Query\SqlTable;
use \PsiFramework\Classes\Util\Database\Query\SqlValue;
use \PsiFramework\Classes\Util\Parameters\ObjectParameters;
use \PsiFramework\Applications\AlloMediaPortal\Classes\Model\SiteMembership;

/**
 * AlloMedia
 * Portail des professionnels
 *
 * @author Rémi San
 * @version beta
 */

/**
 * The SiteMembershipDAO is the Data Access Object for the class SiteMembership
 *
 * @package DAO
 */
class SiteMembershipDAO extends AbstractDAO
{

    protected static $_singleton = null;

    public function retrieveBySiteId(/*AlloMediaSite*/ $site, /*int*/ $idOnSite)
    {
        $table
            = new SqlTable(
                $this->_objectParameters->getTable(),
                $this->_objectParameters->getSchema()
            );
        $idForSiteCol = new SqlColumn('site_user_id', $table);
        $siteId = new SqlColumn('site_id', $table);

        $queryBuilder = new QueryBuilder();
        $queryBuilder->createSelectQuery();
        $queryBuilder->setTable($table);

        $whereClause = new SqlOperation(SqlOperation::$and);
        $whereClause->addParameter(
            new SqlOperation(
                SqlOperation::$equal,
                array($idForSiteCol, new SqlValue($idOnSite))
            )
        );
        $whereClause->addParameter(
            new SqlOperation(
                SqlOperation::$equal,
                array($siteId, new SqlValue($site->getId()))
            )
        );

        $queryBuilder->addWhereClause($whereClause);

        $memberships = $this->processQueryBuilder($queryBuilder);
        if (!is_null($memberships) && count($memberships)>0) {
            return $memberships[0] ;
        } else {
            return null ;
        }
    }

    /**
     * Function to be called instead of the constructor.
     *
     * @return SiteMembershipDAO    instance
     */
    public static function getInstance(ObjectParameters $objectParameters)
    {

        if (self::$_singleton==null) {
            self::$_singleton = new SiteMembershipDAO($objectParameters);
        }

        return self::$_singleton;
    }

}
